<template>
    <div class="person-container">
        <div class="personal-info">
            <h3>个人信息</h3>
            <el-divider />
            <div class="avatar-admin">
                <el-avatar :size="100" :src="person_info.avatar" >
                    <img
                        :src="person_info.avatar"
                    />
                </el-avatar>
            </div>
            <div class="info">
               <div><h4>昵称:</h4><span>{{person_info.nickName}}</span></div>
               <div><h4>角色:</h4><span>{{person_info.role}}</span></div>
               <div><h4>用户名:</h4><span>{{person_info.username}}</span></div>
               <div><h4>创建时间:</h4><span>{{person_info.creationTime}}</span></div>
            </div>
        </div>
        <div class="personal-setting">
            <h3>个人设置</h3>
            <el-divider />
            <div class="form-wrapper">
                <span>上传头像</span>
                <div class="avatar-setting">
                    <el-upload ref="uploadRef" action="#" :limit="1" :on-exceed="handleExceed" list-type="picture" :on-change="file=>handleImgChange(file,fileList,'add')" :on-remove="file=>handleImgChange(file,fileList,'delete')" :auto-upload="false">
                        <div class="choose-area">
                            <Icon icon="upload-image" size="100px" />
                        </div>  
                        <template #file="{ file }">
                            <el-image
                                class="preview-logo"
                                preview-teleported
                                :src="fileUrl"
                                lazy
                                :zoom-rate="1.2"
                                :max-scale="7"
                                :min-scale="0.2"
                                :preview-src-list="[fileUrl]"
                                :initial-index="0"
                                fit="cover"
                                
                            /> 
                            <div class="btn-wrapper" >
                                <div class="icon-wrapper">
                                    <Icon icon="delete" @click="handleRemove" />
                                    <Icon icon="publish-dark" @click="submitAvatar" />
                                </div>
                            </div>
                        </template>
                    </el-upload>
                </div>
                
                <el-form ref="ruleFormRef" :rules="rules" :model="ruleForm" status-icon label-width="80px">
                    <el-form-item label="昵称" prop="nickName">
                        <el-input v-model="ruleForm.nickName" placeholder="昵称请勿包含特殊字符,长度2到10个字符"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitForm">保存</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script setup>
    import { ref, onMounted } from 'vue';
    import {genFileId, ElMessage,ElUpload,ElImage,ElForm,ElFormItem,ElInput,ElButton,ElAvatar,ElDivider,ElMessageBox,ElDialog} from 'element-plus'
    import {editPersonalInfo,uploadAvatar} from '@/api/index.js';
    import Icon  from '@/components/Icon.vue';
    import {useUserStore} from '@/store/modules/user.js';
    const store = useUserStore();
    /*模板引用*/
    const ruleFormRef = ref(null);
    const uploadRef =ref(null);
    //校验昵称
    const checkNickName = (rule, value, callback) => {
      const regex = /[\s~`!@#$%^&*()\\-_=+[\]{}|;:'",<.>/?]/;
      const result = regex.test(value);
      if (result) {
        callback(new Error("昵称中请勿包含特殊字符"));
      } else {
        callback();
      }
    };
    const person_info = store.userInfo;
    const ruleForm = ref({
        nickName:'',
        avatar:''
    });
    const rules = ref({
      nickName:[
        { required: true, message: '请输入昵称', trigger: 'blur' },
        { type:'string',validator:checkNickName, trigger: 'change'},
        { min: 2, max: 10, message: '昵称长度在 2 到 10 个字符', trigger: 'blur' }
      ]  
    });
    let fileUrl = ref('');
    let avatarFile = ref(null);
/*方法*/
//提交表单
const submitForm = () => {
    ruleFormRef.value.validate((valid) => {
      if (valid) {
        editPersonalInfo({nickName:ruleForm.value.nickName}).then((res)=>{
            if(res.status.code === 200){
              ElMessage.success(res.status.msg);
              store.userInfo.nickName = res.data.nickName;
              person_info.nickName = res.data.nickName;
            }else{
              ElMessage.error(res.status.msg);
            }
        })
      } else {
        return false;
      }
    })
}
/*处理图片上传方法*/
//处理图片的改变
const handleImgChange = (file,fileList,type)=>{
    if(type === 'add'){
        fileUrl.value = file.url;
        avatarFile.value = file.raw;
    }else{
        uploadRef.value.clearFiles();
        fileUrl.value = '';
        avatarFile.value = null;
    }
}
//替换之前上传的图片
const handleExceed = (files) => {
      uploadRef.value.clearFiles();
      const file = files[0];
      file.uid = genFileId();
      uploadRef.value.handleStart(file);
}
//关闭预览图片
const handleRemove = () => {
    handleImgChange(null,null,'delete');
    uploadRef.value.clearFiles();
}
//确认上传头像
const submitAvatar = () => {
    if(fileUrl.value.includes('blob:') && avatarFile.value !== null){
        const param = new FormData();
        param.append('avatar',avatarFile.value);
        uploadAvatar(param).then(res=>{
            if(res.status.code ===200){
                ElMessage.success(res.status.msg);
                //将当前头像换成新头像
                store.userInfo.avatar = res.data.avatar;
                person_info.avatar = res.data.avatar;
                handleRemove();
            }else{
                ElMessage.error(res.status.msg);
            }
        });
    }else if(fileUrl.value.includes('/logo/')){
        ElMessage.success('已上传');
    }else{
        ElMessage.error('上传失败');
    }
}
</script>

<style scoped lang='scss'>
:deep(.el-upload-list){
    margin-top:40px;
}
.preview-logo{
    width: 100px;
    height: 100px;
    border-radius:50%;
    border:2px dotted #c7c5c5;
}
.person-container{
    width: 100%;
    height: calc(100% - 20px);
    padding:10px;
    display: flex;
}
.personal-info{
    width:300px;
    display:flex;
    flex-direction: column;
    align-items: center;
    border:1px solid #c7c5c5;
    border-radius: 5px;
    padding: 10px;
    h3{
        margin:10px 0;
        
    }
    .info{
        height:30%;
        width: 100%;
        margin-top:20px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        div{
            padding: 0 5px;
            display: flex;
            justify-content: space-between;
            padding-bottom: 5px;
            border-bottom: 1px solid #dedede;
            span{
                color:#999;
            }
        }
    }
}
 .personal-setting{
    width:calc(100% - 450px);
    border:1px solid #c7c5c5;
    border-radius: 5px;
    margin-left:20px;
    padding: 10px;
    h3{
        margin:20px 0;
    }
    .form-wrapper{
        width:50%;
        span{
            color:#606266;
            font-size: 14px;
        }
        .avatar-setting{
            width:100%;
            margin-bottom: 30px;
            padding-left:100px;
            .icon-wrapper{
                width:70px;
                display:flex;
                justify-content: space-between;
            }
        }
    }
 }   

</style>